package com.itboye.api.controller;

import com.itboye.api.helper.WebFileHelper;
import com.itboye.mybatis.enumtype.FileType;
import com.itboye.mybatis.model.UserPictureModel;
import com.itboye.services.utils.impl.UserPictureService;
import com.itboye.services.utils.interfaces.IUserPictureService;
import com.itboye.system.exception.ByServiceException;
import com.itboye.system.helper.ByConfigHelper;
import com.itboye.system.helper.ByConsoleHelper;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;

/**
 * AvatarController.java
 * Created on  2016/7/30 16:40
 * 版本       修改时间          作者      修改内容
 * V1.0.1    2016/7/30      hebidu    初始版本
 * <p>
 * Copyright (c) 2013 杭州博也网络科技有限公司 版权所有
 * HANGZHOU BOYE TECHNOLOGY CO.,LTD. All Rights Reserved.
 */
@Controller
public class AvatarController {

    @Resource
    private IUserPictureService userPictureService;

    private static final Logger logger = LogManager.getLogger(AvatarController.class.toString());

    /**
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/profile" ,method = RequestMethod.GET)
    public void profile(HttpServletRequest request,HttpServletResponse response){
        String id =  request.getParameter("id");
        if(id == null || id.length() == 0){
            WebFileHelper.writeDefaultPicture(request,response);
            return;
        }
        int uid = Integer.parseInt(id);
        if(uid <= 0){
            WebFileHelper.writeDefaultPicture(request,response);
            return;
        }


        HashMap<String,String> params = new HashMap<String, String>();
        params.put("uid",""+uid);
        params.put("type",FileType.Business_License);

        getUserPictureModel(params,request,response);
    }

    /**
     * 专门的头像接口 , 需要用户ID
     * @param request
     * @param response
     */
    @RequestMapping(value = "/avatar",method = RequestMethod.GET)
    public void view(HttpServletRequest request,HttpServletResponse response){
        String id =  request.getParameter("id");
        if(id == null || id.length() == 0){
            WebFileHelper.writeDefaultPicture(request,response);
            return;
        }
        int uid = Integer.parseInt(id);
        if(uid <= 0){
            WebFileHelper.writeDefaultPicture(request,response);
            return;
        }

        HashMap<String,String> params = new HashMap<String, String>();
        params.put("uid",""+uid);
        params.put("type",FileType.Avatar);

        getUserPictureModel(params,request,response);

    }


    private void getUserPictureModel(HashMap<String,String> params,HttpServletRequest request,HttpServletResponse response){

        try {
            UserPictureModel userPictureModel = userPictureService.getInfoBy(params);
            System.out.println(userPictureModel);
            if (userPictureModel == null) {
                WebFileHelper.writeDefaultPicture(request, response);
                return;
            }

            String path = userPictureModel.getPath();
            String realPath = "";//request.getSession().getServletContext().getRealPath("");
            realPath = realPath + ByConfigHelper.getInstance().getUploadFilePath() + path;

            File file = new File(realPath);

            if (!file.exists() || !file.canRead()) {
                WebFileHelper.writeDefaultPicture(request, response);
                return;
            }
            String ext = userPictureModel.getExt();
            if (ext == null || ext.length() == 0) {
                ext = "png";
            }
            if (ext.startsWith(".")) {
                ext = ext.substring(1);
            }

            //TODO: 根据ext来设置content-Type
            response.setContentType("image/" + ext);

            WebFileHelper.writeFile(file,response);
        }catch (ByServiceException e){
            ByConsoleHelper.info(e.getLocalizedMessage(),logger);
            WebFileHelper.writeDefaultPicture(request, response);
        }finally {

        }
    }

}
